from django.contrib.auth import get_user_model
from django.db import IntegrityError
from django.db.models import Sum
from rest_framework import permissions, status
from rest_framework.decorators import api_view
from rest_framework.generics import CreateAPIView, RetrieveAPIView, RetrieveUpdateAPIView, ListAPIView, DestroyAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from account.models import FocusUser
from account.serializer import UserDetailSer, UserCreateSer, UserUpdateSer, UserDeleteSer, UserFocusListSer, \
    UserFocusCreateSer, UserFocusDeletSer, UserFocusedListSer
from answer.models import Answer, AnswerFocus
from answer.serializer import AnswerDetailSer
from questions.models import Question, QuestionFocus
from questions.serializer import QuestionDetailSer
from tag.models import Tag
from utils.permission import IsOwnerOrReadOnly

User = get_user_model()


class UserCreateView(CreateAPIView):
    permission_classes = [
        permissions.AllowAny
    ]
    serializer_class = UserCreateSer


class UserDetailView(RetrieveAPIView):
    lookup_field = 'phone'
    serializer_class = UserDetailSer
    queryset = User.objects.all()


class UserUpdateView(RetrieveUpdateAPIView):
    serializer_class = UserUpdateSer
    queryset = User.objects.all()


class UserListView(ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserDetailSer


class UserDeleteView(DestroyAPIView):
    queryset = User.objects.all()
    serializer_class = UserDeleteSer


class UserAnswerListView(ListAPIView):
    serializer_class = AnswerDetailSer

    def get_queryset(self):
        user = self.request.user
        answers = Answer.objects.filter(creator=user).order_by('-created_time')
        return answers


class UserQuestionListView(ListAPIView):
    serializer_class = QuestionDetailSer

    def get_queryset(self):
        user = self.request.user
        questions = Question.objects.filter(creator=user).order_by('-created_time')
        return questions


@api_view(['GET'])
def user_count(request, **kwargs):
    phone = kwargs.get('phone')
    try:
        user = User.objects.get(phone=phone)
    except User.DoesNotExist:
        return Response({'detail':'user is not exists'})
    jiben_data = UserDetailSer(user).data
    question_count = Question.objects.filter(creator=user).count()
    answer = Answer.objects.filter(creator=user)
    answer_count = answer.count()
    praise_count = answer.aggregate(Sum('praise')).get('praise__sum', '0')
    question_focus_count = QuestionFocus.objects.filter(creator=user).count()
    answer_focus_count = AnswerFocus.objects.filter(creator=user).count()
    user_focus_count = FocusUser.objects.filter(creator=user).count()
    jiben_count = {'question_count': question_count,
                     'answer_count': answer_count,
                     'praise_count': praise_count,
                     'question_focus_count': question_focus_count,
                     'answer_focus_count': answer_focus_count,
                     'user_focus_count': user_focus_count}
    jiben_data.update(jiben_count)
    return Response(jiben_data)


class UserFocusListView(ListAPIView):
    serializer_class = UserFocusListSer

    def get_queryset(self):
        user = self.request.user
        queryset = FocusUser.objects.filter(focus_user__creator=user).order_by('-created_time')
        return queryset


class UserFocusedListView(ListAPIView):
    serializer_class = UserDetailSer

    def get_queryset(self):
        user = self.request.user
        queryset = User.objects.filter(focus_user__focused=user).order_by('-created_time')
        return queryset


class UserFocusCreateView(CreateAPIView):
    serializer_class = UserFocusCreateSer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        focus_id = self.request.data.get('focus_id')
        try:
            focus = User.objects.get(id=focus_id)
            serializer.save(focused=focus)
        except User.DoesNotExist:
            return Response({"detail": "user does not exist"})
        except IntegrityError:
            return Response({"detail": "This user has been concerned"})
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class UserFocusDeleteView(DestroyAPIView):
    lookup_field = 'focused'
    permission_classes = (IsOwnerOrReadOnly,)
    queryset = FocusUser.objects.all()
    serializer_class = UserFocusDeletSer




class PostUserTagView(APIView):

    def post(self, request, **kwargs):
        user = request.user
        tag_name = request.data.get('expertise_area')
        try:
            tag = Tag.objects.get(name=tag_name)
        except Tag.DoesNotExist:
            return Response({'detail': 'tag has not exist'}, status=400)
        user.expertise_area = tag
        user.save()
        return Response(UserDetailSer(user).data)
